# -*- encoding: utf-8 -*-
# machine_status.py  获取本机资源使用信息、进程状态和连接情况
# created by vince67 (nuovince@gmail.com)
# May 2014
 
 
import datetime
import json
import os

try:
    import psutil as ps           
except ImportError, e:
    logging.error(e)
    logging.info ("Now downloading psutil module...")
    os.system("pip install psutil")
    import psutil as ps

import time
import socket
import uuid
 

class _IncMachineStatus:
    def __new__(cls, *args, **kwads):
        if not hasattr(cls, "_instance"):
            print ("create once!")
            inc = super(MachineStatus, cls)
            cls._instance = inc.__new__(cls, *args, **kwads)
        return cls._instance


class MachineStatus(_IncMachineStatus):
    def __new__(cls, *args, **kwads):
        if not hasattr(cls, "_instance"):
            print ("create once!")
            inc = super(MachineStatus, cls)
            cls._instance = inc.__new__(cls, *args, **kwads)
        return cls._instance

    #   初始化
    def __init__(self):
        self.MAC = None
        self.IP = None
        self.cpu = {}
        self.mem = {}
        self.process = {}
        self.network = {}
        self.status = []                    #  [cpu使用率， 内存使用率， 进程数目， established连接数]
     
    #  宿主机存库状态
    def update_statu(self):
        self.get_init_info()
        self.get_status_info()

        #todo save to db / redis
        self.save_status_to_db()

    def save_status_to_db(self):
        print self.status
 
    #  数据收集
    def get_init_info(self):
        self.cpu = {'cores' : 0,            #  cpu逻辑核数
                    'percent' : 0          #  cpu使用率
                    } 
        self.mem = {'percent' : 0,
                    'total' : 0,
                    'vailable' : 0,
                    'used' : 0,
                    'free' : 0}
        self.process = {'count' : 0,        #  进程数目
                        'pids' : 0}         #  进程识别号
        self.network = {'count' : 0,        #  连接总数
                        'established' : 0}  #  established连接数
        self.status = [0, 0, 0, 0]          #  cpu使用率，内存使用率， 进程数， established连接数
        self.get_mac_address()
        self.get_ip_address()
 
    #  获取状态列表
    def get_status_info(self):
        self.get_cpu_info()
        self.get_mem_info()
        self.get_process_info()
        self.get_network_info()
        self.status[0] = self.cpu['percent']
        self.status[1] = self.mem['percent']
        self.status[2] = self.process['count']
        self.status[3] = self.network['established']
 
    #  获取mac
    def get_mac_address(self):
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        self.MAC = ":".join([mac[e : e+2] for e in range(0, 11, 2)])
 
    #  获取ip
    def get_ip_address(self):
        tempSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        tempSock.connect(('8.8.8.8', 80))
        addr = tempSock.getsockname()[0]
        tempSock.close()
        self.IP = addr
 
    #  获得cpu信息
    def get_cpu_info(self):
        self.cpu['cores'] = ps.cpu_count()
        self.cpu['percent'] = ps.cpu_percent(interval=2)

    #  获得memory信息
    def get_mem_info(self):
        mem_info = ps.virtual_memory()
        self.mem['percent'] = mem_info.percent
        self.mem['total'] = mem_info.total
        self.mem['vailable'] = mem_info.available
        self.mem['used'] = mem_info.used
        self.mem['free'] = mem_info.free

    #  获取进程信息
    def get_process_info(self):
       pids = ps.pids()
       self.process['pids'] = pids
       self.process['count'] = len(pids)
 
    #  获取网络数据
    def get_network_info(self):
        conns = ps.net_connections()
        self.network['count'] = len(conns)
        count = 0
        for conn in conns:
           if conn.status is 'ESTABLISHED':
               count = count + 1
        self.network['established'] = count
 
if __name__ == '__main__':
    import time 
    MS = MachineStatus()
    MS.update_statu()
    
    print MS.IP, '\n', MS.MAC, '\n', MS.cpu, '\n', MS.mem, '\n', MS.status